<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis as Redis;
use App\Models\PasswordCoupon;
use App\Interfaces\PasswordCouponService;
use App\Exceptions\Interfaces\PasswordCouponServiceException;
use App\Interfaces\SmsService;


/**
 * 口令优惠券
 * author:leen
 * date:2016-08-18
 */
class PasswordCouponController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        dd('口令优惠券');
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update($password, Request $request, PasswordCouponService $passwordCouponService)
    {

        $return= ['status' => 1, 'message' => '', 'data' => ''];

        $password_status = $request->password_status;      //口令状态,0:未发送,1:已发送,2:已激活;

        $send_time = $request->send_time;      //发送时间

        $user_id = $request->user_id;      //要绑定的用户id

        $use_time = $request->use_time;      //用户激活时间


        try {

            $password_coupon = $passwordCouponService->updatePwds($password, $password_status, $send_time, $user_id, $use_time);

            $return['message'] = '更新成功';

            $return['data'] = $password_coupon;

        } catch (PasswordCouponServiceException $e) {

            $return['status'] = 0;

            $return['message'] = $e->getMessage();

            return $return;
        }

        return $return;

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function createPwds($pwd_num, $coupon_id, Request $request, PasswordCouponService $passwordCouponService)
    {

        $return= ['status' => 1, 'message' => '', 'data' => ''];

        try {

            $password = $passwordCouponService->createPwds($pwd_num, $coupon_id);

            $return['message'] = '生成成功';

            $return['data'] = $password;

        } catch (PasswordCouponServiceException $e) {

            $return['status'] = 0;

            $return['message'] = $e->getMessage();

            return $return;
        }

        return $return;

    }

    /**
     * 使用递归方法获取与数据库中不重复的口令值
     * @param  [type]  $password [口令值]
     * @param  integer $length   [口令长度]
     * @return [type]            [description]
     */
    public function getNoRepeatStr($password = '', $length=0)
    {

        if ($length>0) {

            $pwd_str = getUuid($length);           //获取随机字符串，默认32位，可以带上要获取的字符串的长度，如：getUuid(15)
        }else{

            $pwd_str = getUuid();                  //获取随机字符串，默认32位，可以带上要获取的字符串的长度，如：getUuid(15)
        }


        if ($password) {

            $lrange = PasswordCoupon::find($password);              //获取一条hash记录的所有字段信息

            if ($lrange) {

                $pwd_str = $this->getNoRepeatStr($password);
            }
        }

        return $pwd_str;
    }


    /**
     * 获取指定优惠券的口令
     * 获取指定优惠券口令不同状态的数量
     * @param  integer $search [查询条件数组]
     * @return [type]          [description]
     */
    public function getPwdsByCouponId(Request $request, PasswordCouponService $passwordCouponService)
    {

        $return= ['status' => 1, 'message' => '', 'data' => ''];

        $coupon_id = $request->coupon_id;

        $password_status = $request->password_status;

        if (empty($coupon_id)) {

            $return['status'] = 0;

            $return['message'] = '优惠券id不能为空';

            return $return;
        }

        $status = [ 0, 1, 2];           //口令的状态，0:未发送, 1:已发送, 2:已激活;

        // $password_status = empty($password_status) ? 0 : $password_status;

        // $return['data'] = $passwordCouponService->getPwds($coupon_id, $password_status);

        foreach ($status as $key => $password_status) {

            $password_coupons = $passwordCouponService->getPwds($coupon_id, $password_status);
            $result[$password_status] = $password_coupons->count();
        }

        $return['data'] = $result;

        return $return;
    }

    /**
     * 获取未发送的口令的优惠券列表
     * @return [type]            [description]
     */
    public function getCouponNoSend(PasswordCouponService $passwordCouponService)
    {

        return $passwordCouponService->getCouponNoSend();
    }


    /**
     * 发送优惠口令给用户
     * @param  [type] $user_status [筛选用户的条件，0:所有用户; 1:近3个月登录用户; 2:邮箱注册用户;]
     * @param  [type] $coupon_id   [要发送口令的优惠券id]
     * @return [type]              [description]
     */
    public function sendPwdsToUser(Request $request, SmsService $smsService, PasswordCouponService $passwordCouponService)
    {

        $return= ['status' => 1, 'message' => '发送成功', 'data' => ''];

        $user_stauts = $request->user_status;

        $coupon_id = $request->coupon_id;

        $user_stauts = empty($request->user_status) ? 0 : $request->user_status;

        $password_status = 0;           //口令的状态，0:未发送, 1:已发送, 2:已激活;

        if (empty($coupon_id)) {

            $return['status'] = 0;

            $return['message'] = '要发送口令的优惠券id不能为空';

            return $return;
        }

        $phones = $smsService->getPhoneByObject($user_stauts);          //用户手机号码集合      user_stauts：0:所有用户; 1:近3个月登录用户; 2:邮箱注册用户;

        $pwds =  $passwordCouponService->getPwds($coupon_id, $password_status);         //获取指定优惠券未发送的口令
        if (count($pwds)>0) {

            // $pwds = $pwds->toArray();
            foreach ($pwds as $key => $value) {

                $passwords[$key] = $value['password'];
            }
        }else{

            $return['status'] = 0;

            $return['message'] = '该优惠券没有可发送的口令';

            return $return;
        }


        //第一步：将口令和用户对应

        $user_msgs = [];        //要发送的号码和内容数组

        $user_pwds = [];        //号码和对应的口令数组

// $phones = ['15136168236', '', '17737132820'];

// $pwds = ['E6E78AFB96BC0D5F636B72BFF240214C', '46026560266856FD79F152A65727BCFA', 'A2201620AF8F7034353F88230B0DADC8'];

        $phones = formatArray($phones);

        $passwords = formatArray($passwords);

        foreach ($phones as $phones_key => $phones_value) {


            if (empty($phones_value)) {

                break;
            }

            if (empty($passwords[$phones_key])) {

                break;
            }

            $pwds_value = $passwords[$phones_key];

            $user_msgs[$phones_value] = '恭喜您！获得一个优惠口令：'.$pwds_value;

            $user_pwds[$phones_value] = $pwds_value;
        }


        //第二步：调用批量发送短信接口
        // $result = [ "15136168236" => 1000, "17737132820" => 1000];
        $result = $smsService->sendMassMsg($user_msgs);


        //第三步：根据发送短信接口返回的结果更改口令状态

        foreach ($result as $key => $value) {

            $password = $user_pwds[$key];

            /*echo '<BR><BR>key:'.$key;

            echo '<BR>value:'.$value;

            echo '<BR>pwds str:'.$password;*/

            if ($value == 1000) {

                //发送成功
                $password_status = 1;      //口令状态,0:未发送,1:已发送,2:已激活;

                $send_time = date('Y-m-d H:i:s');

                $password_coupon = $passwordCouponService->updatePwds($password, $password_status, $send_time);
            }else{

                //发送失败

                $return['status'] = 0;

                $return['message'] = '口令发送失败';

                return $return;
            }

        }

        $return['status'] = $result;

        return $return;
    }

}
